<template>
  <div>
    <el-form :model="form1" ref="form1" label-width="100px">
      <el-form-item label="选择会员：">
        <el-form :model="formInline" ref="formInline" label-width="100px">
          <div style="width:100%;color:gray;">
            所在大区：
            <el-select
              v-model="formInline.warzone"
              multiple
              collapse-tags
              style="width:200px;"
            >
              <el-option
                v-for="item in warzoneList"
                :key="item.orgSeq"
                :label="item.orgName"
                :value="item.orgSeq"
              ></el-option> </el-select
            >&nbsp;&nbsp; 会员等级：
            <el-select
              v-model="formInline.memberLevel"
              multiple
              collapse-tags
              style="width:200px;"
            >
              <el-option
                v-for="item in memberLevelList"
                :key="item.uuid"
                :label="item.gradelevelName"
                :value="item.uuid"
              ></el-option> </el-select
            >&nbsp;&nbsp; 绑定状态：
            <el-select
              v-model="formInline.bindStatus"
              multiple
              collapse-tags
              style="width:200px;"
            >
              <el-option label="强绑定" value="1"></el-option>
              <el-option label="弱绑定" value="2"></el-option>
              <el-option label="已流失" value="3"></el-option>
            </el-select>
          </div>
          <div style="width:100%;color:gray;margin:5px 0px 8px 0px;">
            会员信息：
            <el-input
              v-model="formInline.keyword"
              placeholder="会员名称/备注/手机"
              style="width:200px;"
            ></el-input
            >&nbsp;&nbsp; 注册时间：
            <el-date-picker
              v-model="formInline.registerTimeBegin"
              type="date"
              value-format="yyyy-MM-dd"
              style="width:150px;"
            ></el-date-picker
            >至
            <el-date-picker
              v-model="formInline.registerTimeEnd"
              type="date"
              value-format="yyyy-MM-dd"
              style="width:150px;"
            ></el-date-picker>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="search()"
              size="mini"
              >查询</el-button
            >
          </div>
        </el-form>
        <el-table
          :data="tableData"
          @selection-change="memberChecked"
          style="width:100%;"
          height="300"
          border
          :header-cell-style="{ background: '#ebecf0', color: '#606266' }"
        >
          <el-table-column
            type="selection"
            width="55"
            align="center"
            fixed
          ></el-table-column>
          <el-table-column
            type="index"
            width="60"
            label="序号"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="userName"
            label="姓名"
            header-align="center"
          ></el-table-column>
          <el-table-column
            prop="nickName"
            label="昵称"
            header-align="center"
          ></el-table-column>
          <el-table-column prop="sex" label="性别" align="center" width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.sex == 1">男</span>
              <span v-if="scope.row.sex == 2">女</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="cellPhoneNo"
            label="手机号"
            header-align="center"
          ></el-table-column>
          <!--<el-table-column prop="orgSeq" label="所在大区" align="center"></el-table-column>-->
          <el-table-column
            prop="gradeLevel"
            label="会员等级"
            header-align="center"
          ></el-table-column>
          <el-table-column prop="status" label="绑定状态" header-align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.bdstatus == 1">强绑定</span>
              <span v-if="scope.row.bdstatus == 2">弱绑定</span>
              <span v-if="scope.row.bdstatus == 3">已流失</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="注册时间"
            header-align="center"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="remarkName"
            label="备注"
            header-align="center"
            width="220"
          ></el-table-column>
        </el-table>

        <div class="block" style="margin-top:5px;">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :page-sizes="[10, 20, 30, 50, 100]"
            :current-page="listQuery.current"
            :page-size="listQuery.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </el-form-item>

      <el-form-item label="选择卡券：">
        <el-form :model="couponForm" ref="couponForm" label-width="100px">
          <div style="width:100%;color:gray;margin:0px 0px 8px 0px;">
            卡券名称：
            <el-input
              v-model="couponForm.couponName"
              placeholder="卡券名称/编号"
              style="width:200px;"
            ></el-input>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="getCouponList()"
              size="mini"
              >查询</el-button
            >
          </div>
        </el-form>
        <el-table
          :data="couponList"
          @selection-change="couponChecked"
          border
          style="width:100%;"
          height="300"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        >
          <el-table-column
            type="selection"
            width="55"
            align="center"
            fixed
          ></el-table-column>
          <el-table-column
            type="index"
            width="60"
            label="序号"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="couponName"
            label="卡券名称"
            width="200"
            header-align="center"
          ></el-table-column>
          <el-table-column
            prop="couponSeq"
            label="卡券编号"
            width="160"
            header-align="center"
          ></el-table-column>
          <el-table-column
            prop="couponMoney"
            label="卡券面值"
            width="150"
            header-align="center"
            align="left"
          >
            <template slot-scope="scope">
              <span
                >满{{ scope.row.conponLimitMoney }}减{{
                  scope.row.couponMoney
                }}元</span
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="validType"
            label="有效期类型"
            width="180"
            align="center"
          >
            <template slot-scope="scope">
              <el-radio-group v-model="scope.row.validType">
                <el-radio-button label="1">天数</el-radio-button>
                <el-radio-button label="2">日期</el-radio-button>
              </el-radio-group>
            </template>
          </el-table-column>
          <el-table-column prop="validDate" label="有效期" align="center">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.validDate"
                @blur="numberBlur($event, '有效天数')"
                v-if="scope.row.validType == 1"
                style="width:100px;text-align:right;text-align-last:right;"
                placeholder
              ></el-input>
              <el-date-picker
                v-model="scope.row.validCreateDate"
                v-if="scope.row.validType == 2"
                type="date"
                value-format="yyyy-MM-dd"
                style="width:140px;"
                placeholder="请选择生效时间"
              ></el-date-picker>
              <el-date-picker
                v-model="scope.row.validEndDate"
                v-if="scope.row.validType == 2"
                type="date"
                value-format="yyyy-MM-dd"
                style="width:140px;"
                placeholder="请选择失效时间"
              ></el-date-picker>
            </template>
          </el-table-column>
          <el-table-column
            prop="limitQuantity"
            label="发放数量"
            width="130"
            align="center"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.limitQuantity"
                :value="scope.row.limitQuantity"
                @blur="numberBlur($event, '发放数量')"
                style="width:80px;text-align:right;text-align-last:right;"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="卡券状态" align="center" width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.status == '1'">启用</span>
              <span v-if="scope.row.status == '0'">停用</span>
              <span v-if="scope.row.status == '2'">已删除</span>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item label="发送说明：">
        <el-input
          type="textarea"
          v-model="form1.sendRemark"
          placeholder="请输入发送说明"
          maxlength="100"
          show-word-limit
          :autosize="{ minRows: 3 }"
          style="width:80%;"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="send(2)">给选中会员发券</el-button>
        <el-button type="primary" @click="send(1)">给全部会员发券</el-button>
        <el-button @click="goback()">取 消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  queryMemberInformation,
  getWarzoneList,
  queryCouponList,
  createSendRecord,
} from '@/api/promotionProgramEdit';
import { queryGradelevelRule } from '@/api/membergrade';

export default {
  data() {
    return {
      logininfo: {},
      orgList: [],
      orgSeq: '',
      loading: true,
      formInline: {
        warzone: [],
        memberLevel: [],
        bindStatus: [],
        registerTimeBegin: '',
        registerTimeEnd: '',
        keyword: '',
      },
      form1: {
        sendRemark: '',
      },
      couponForm: {
        couponName: '',
      },
      total: 0,
      userId: '',
      listQuery: {
        current: 1,
        size: 10,
      },
      tableData: [],
      lsMemberList: [],
      warzoneList: [],
      memberLevelList: [],
      couponList: [],
      lsCouponList: [],
    };
  },
  mounted() {
    this.logininfo = localStorage.getItem('logininfo');
    this.orgList = JSON.parse(this.logininfo).orgList;
    this.orgSeq = this.orgList[0].orgSeq;
    this.getWarzoneList();
    this.getMemberlevel();
    this.getMemberList();
    this.getCouponList();
  },
  methods: {
    goback() {
      this.$router.go('-1');
    },
    handleSizeChange(val) {
      this.listQuery.size = val;
      this.getMemberList();
    },
    handleCurrentChange(val) {
      this.listQuery.current = val;
      this.getMemberList();
    },
    numberBlur(e, name) {
      if (e.target.value == '') {
        return;
      }
      let flag = new RegExp('^[1-9][0-9]*$').test(e.target.value);
      if (!flag) {
        this.$message({
          message: name + '请输入正整数',
          type: 'warning',
        });
        e.target.value = '';
      }
    },
    search() {
      this.listQuery.current = 1;
      this.getMemberList();
    },
    getWarzoneList() {
      let data = {};
      getWarzoneList(data).then((res) => {
        this.warzoneList = res.records;
      });
    },
    getMemberlevel() {
      let data = {
        size: 100,
        current: 1,
        condition: {},
        ascs: [],
        descs: [],
      };
      queryGradelevelRule(data).then((res) => {
        this.memberLevelList = res.records;
      });
    },
    getMemberList() {
      let data = {
        size: this.listQuery.size,
        current: this.listQuery.current,
        condition: {
          orgSeqs: this.formInline.warzone,
          memberLevelIds: this.formInline.memberLevel,
          bindStatus: this.formInline.bindStatus,
          registerTimeBegin: this.formInline.registerTimeBegin,
          registerTimeEnd: this.formInline.registerTimeEnd,
          keyword: this.formInline.keyword,
        },
        ascs: [],
        descs: [],
      };
      console.log('查询会员');
      console.log(data);
      queryMemberInformation(data).then((res) => {
        console.log(res.records);
        this.loading = false;
        this.tableData = res.records;
        this.total = res.total;
      });
    },
    getCouponList() {
      let data = {
        size: 100,
        current: 1,
        condition: {
          status: 1,
          couponType: 1,
          couponName: this.couponForm.couponName,
        },
        ascs: [],
        descs: [],
      };
      queryCouponList(data).then((res) => {
        for (var i in res.records) {
          res.records[i].validType = '1';
          res.records[i].validDate = '';
          res.records[i].limitQuantity = '1';
        }
        this.couponList = res.records;
      });
    },
    memberChecked(row) {
      this.lsMemberList = row;
    },
    couponChecked(row) {
      this.lsCouponList = row;
    },
    send(flag) {
      if (flag == 2) {
        // 选中会员
        if (this.lsMemberList == null || this.lsMemberList.length == 0) {
          this.$message({ message: '请先选择要发券的会员', type: 'warning' });
          return;
        }
        if (this.lsCouponList == null || this.lsCouponList.length == 0) {
          this.$message({ message: '请选择要发送的优惠券', type: 'warning' });
          return;
        }
      } else {
        // 全部会员
        if (this.lsCouponList == null || this.lsCouponList.length == 0) {
          this.$message({ message: '请选择要发送的优惠券', type: 'warning' });
          return;
        }
      }
      // 校验录入内容
      var flag1 = true;
      var flag2 = true;
      var flag3 = true;
      var flag4 = true;
      var flag5 = true;
      let r = new RegExp('^[1-9][0-9]*$');
      for (var i in this.lsCouponList) {
        var validType = this.lsCouponList[i].validType;
        var validDate = this.lsCouponList[i].validDate;
        var begin = this.lsCouponList[i].validCreateDate;
        var end = this.lsCouponList[i].validEndDate;
        var quantity = this.lsCouponList[i].limitQuantity;
        if (validType == 1) {
          if (validDate == null || validDate == '' || !r.test(validDate)) {
            flag1 = false;
            break;
          }
        }
        if (validType == 2) {
          if (begin == null || begin == '') {
            flag2 = false;
            break;
          }
          if (end == null || end == '') {
            flag3 = false;
            break;
          }
          if (end < begin) {
            flag5 = false;
          }
        }
        if (quantity == null || quantity == '' || !r.test(quantity)) {
          flag4 = false;
          break;
        }
      }
      if (!flag1) {
        this.$message({
          message: '请正确输入已选优惠券的有效天数',
          type: 'warning',
        });
        return;
      }
      if (!flag2) {
        this.$message({
          message: '请输入已选优惠券的生效日期',
          type: 'warning',
        });
        return;
      }
      if (!flag3) {
        this.$message({
          message: '请输入已选优惠券的失效日期',
          type: 'warning',
        });
        return;
      }
      if (!flag5) {
        this.$message({ message: '失效日期不能早于生效日期', type: 'warning' });
        return;
      }
      if (!flag4) {
        this.$message({
          message: '请正确输入已选优惠券的发放数量',
          type: 'warning',
        });
        return;
      }
      for (var i in this.lsCouponList) {
        this.lsCouponList[i]['num'] = this.lsCouponList[i].limitQuantity;
        delete this.lsCouponList[i].code;
        delete this.lsCouponList[i].comments;
        delete this.lsCouponList[i].couponDiscount;
        delete this.lsCouponList[i].couponPicture;
        delete this.lsCouponList[i].createTime;
        delete this.lsCouponList[i].createUser;
        delete this.lsCouponList[i].beginTime;
        delete this.lsCouponList[i].endTime;
        delete this.lsCouponList[i].goodsId;
        delete this.lsCouponList[i].goodsIds;
        delete this.lsCouponList[i].isEnd;
        delete this.lsCouponList[i].isNew;
        delete this.lsCouponList[i].isStore;
        delete this.lsCouponList[i].kcAmount;
        delete this.lsCouponList[i].memberGoodsInfoDTOS;
        delete this.lsCouponList[i].planId;
        delete this.lsCouponList[i].receiveCount;
        delete this.lsCouponList[i].shelvesStatus;
        delete this.lsCouponList[i].storeGradelevelRuleDTOS;
        delete this.lsCouponList[i].storeLevelId;
        delete this.lsCouponList[i].updateTime;
        delete this.lsCouponList[i].updateUser;
        delete this.lsCouponList[i].useScope;
        delete this.lsCouponList[i].used;
        delete this.lsCouponList[i].userStoreInfoDTOS;
        delete this.lsCouponList[i].zqOrgSeq;
      }
      var members = [];
      for (var i in this.lsMemberList) {
        members[i] = this.lsMemberList[i].memberId;
      }
      var data = {
        sendRemark: this.form1.sendRemark,
        sendType: flag,
        warzoneList: this.formInline.warzone,
        memberLevelList: this.formInline.memberLevel,
        bindStatus: this.formInline.bindStatus,
        keyword: this.formInline.keyword,
        regBeginDate: this.formInline.registerTimeBegin,
        regEndDate: this.formInline.registerTimeEnd,
        memberList: members,
        couponList: this.lsCouponList,
      };
      // 提交
      // console.log("submit data");
      // console.log(data);
      this.$confirm('确定给所选会员发放所选优惠券吗？', '提示', {
        confirmButtonText: '确定发放',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          createSendRecord(data).then((res) => {
            if (res.code == '1') {
              this.$message({
                showClose: true,
                message: '发放成功',
                type: 'success',
              });
              this.$router.push('sendCouponRecord');
            } else {
              this.$message({
                showClose: true,
                message: '发放失败',
                type: 'success',
              });
            }
          });
        })
        .catch(() => {});
    },
  },
};
</script>
<style lang="less" scoped>
.toptitle {
  border: 1px solid #e0e0e0;
  border-bottom: 2px solid #188097;
  background: #f5f5f5;
  line-height: 35px;
  margin-bottom: 10px;
  padding: 0 10px;
  font-size: 14px;
  font-weight: bold;
}
.el-input--small .el-input__inner {
  height: 32px;
  line-height: 32px;
}
.demo-form-inline {
  //   border: 1px solid #ebeef5;
  padding: 20px 10px 0px 30px;
}
</style>
